﻿namespace Novel_Reading
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.Win32;
    using Novel_Reading.Entity;
    using System.Linq;
    using EpubReader.Entity;
    using EpubReader;
    using Novel_Reading.Enmu;
    using System.Reflection;

    /// <summary>
    /// Interaction logic for NovelReadingWindowControl.
    /// </summary>
    public partial class NovelReadingWindowControl : UserControl, INotifyPropertyChanged
    {
        /// <summary>
        /// 屏蔽js错误
        /// </summary>
        /// <param name="webBrowser">WebBrowser名称</param>
        /// <param name="hide">是否屏蔽错误</param>
        public static void SuppressScriptErrors(WebBrowser webBrowser, bool hide)
        {
            FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fiComWebBrowser == null) return;

            object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
            Console.WriteLine("执行了：SuppressScriptErrors方法，objComWebBrowser == null是" + objComWebBrowser == null + "时间是：" + DateTime.Now.ToString());

            if (objComWebBrowser == null) return;

            objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NovelReadingWindowControl"/> class.
        /// </summary>
        public NovelReadingWindowControl()
        {
            this.InitializeComponent();
            SuppressScriptErrors(webBrowser, true);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// 一般实现通知办法
        /// </summary>
        /// <param name="propertyName"></param>
        public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #region 预定义

        private bool _IsMenuChecked = false;
        /// <summary>
        /// 菜单被选中
        /// </summary>
        public bool IsMenuChecked
        {
            get
            {
                return _IsMenuChecked;
            }
            set
            {
                _IsMenuChecked = value;
                if (value)
                    ScrollViewerMainText1.Visibility = Visibility.Collapsed;
                RaisePropertyChanged();
            }
        }
        private bool _IsCatalogChecked = false;
        /// <summary>
        /// 目录被选择
        /// </summary>
        public bool IsCatalogChecked
        {
            get
            {
                return _IsCatalogChecked;
            }
            set
            {
                _IsCatalogChecked = value;
                if (value)
                    ScrollViewerMainText1.Visibility = Visibility.Collapsed;
                RaisePropertyChanged();
            }
        }

        private string _Catalog = string.Empty;
        /// <summary>
        /// 目录关键字
        /// </summary>
        public string Catalog
        {
            get
            {
                return _Catalog;
            }
            set
            {
                _Catalog = value;
                RaisePropertyChanged();
            }
        }

        private string _FilePath = string.Empty;
        /// <summary>
        /// 文件路径
        /// </summary>
        public string FilePath
        {
            get
            {
                return _FilePath;
            }
            set
            {
                _FilePath = value;
                RaisePropertyChanged();
            }
        }
        private string _ContentText = string.Empty;
        /// <summary>
        /// 文本正文
        /// </summary>
        public string ContentText
        {
            get
            {
                return _ContentText;
            }
            set
            {
                _ContentText = value;
                RaisePropertyChanged();
            }
        }
        private List<ChapterEntity> _ChapterEntityList = new List<ChapterEntity>();
        /// <summary>
        /// 章节目录
        /// </summary>
        public List<ChapterEntity> ChapterEntityList
        {
            get
            {
                return _ChapterEntityList;
            }
            set
            {
                _ChapterEntityList = value;
            }
        }
        /// <summary>
        /// 打开并读取文件
        /// </summary>
        private string AllContent { get; set; }
        private List<CatalogEntity> _CatalogList = new List<CatalogEntity>();
        /// <summary>
        /// 目录列表
        /// </summary>
        public List<CatalogEntity> CatalogList
        {
            get
            {
                return _CatalogList;
            }
            set
            {
                _CatalogList = value;
                RaisePropertyChanged();
            }
        }
        private List<ContentEntity> contentEntitiyList = new List<ContentEntity>();
        /// <summary>
        /// 文本
        /// </summary>
        public List<ContentEntity> ContentEntitiyList
        {
            get
            {
                return contentEntitiyList;
            }
            set
            {
                contentEntitiyList = value;
                RaisePropertyChanged();
            }
        }
        public List<ContentEntity> TempList = new List<ContentEntity>();
        public ContentEntity CurrentContent { get; set; }
        /// <summary>
        /// 当前章节
        /// </summary>
        public ChapterEntity CurrentChapterEntity { get; set; }
        /// <summary>
        /// 当前文档格式
        /// </summary>
        public TextEnmu CurrentMode { get; set; }
        #endregion

        #region 命令

        private RelayCommand _OpenFileCommand;
        /// <summary>
        /// 打开文件命令
        /// </summary>
        public RelayCommand OpenFileCommand
        {
            get
            {
                return _OpenFileCommand ?? (_OpenFileCommand = new RelayCommand(() =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    bool? result = openFileDialog.ShowDialog();
                    if ((bool)result)
                    {
                        FilePath = openFileDialog.FileName;
                        FileInfo fileInfo = new FileInfo(FilePath);
                        if (fileInfo.Extension == ".epub")
                        {
                            //如果是epub电子书。。
                            CurrentMode = TextEnmu.Epub;
                            ChapterEntityList = EpubReaders.LoadEpubFile(FilePath);
                            if (ChapterEntityList != null && ChapterEntityList.Count > 0)
                            {
                                var data = new List<CatalogEntity>();
                                ChapterEntityList.ForEach(p =>
                                {
                                    CatalogEntity catalogEntity = new CatalogEntity();
                                    catalogEntity.CataLogId = p.ChapterId;
                                    catalogEntity.CataLogName = p.ChapterText;
                                    catalogEntity.CataLogSource = p.ContentSource;
                                    data.Add(catalogEntity);
                                });
                                CatalogList = data;
                            }
                        }
                        else
                        {
                            CurrentMode = TextEnmu.Text;
                            CurrentContent = new ContentEntity();
                            ContentText = string.Empty;
                            AllContent = File.ReadAllText(FilePath, Encoding.UTF8);
                            ProcessingText();
                        }
                    }
                }));
            }
        }

        private RelayCommand<string> _CataLogCommand;
        /// <summary>
        /// 目录点击
        /// </summary>
        public RelayCommand<string> CataLogCommand
        {
            get
            {
                return _CataLogCommand ?? (_CataLogCommand = new RelayCommand<string>((p) =>
                {
                    Console.WriteLine(p);
                    switch (CurrentMode)
                    {
                        case TextEnmu.Text:
                            {
                                ScrollViewerMainText.Visibility = Visibility.Visible;
                                ScrollViewerMainText1.Visibility = Visibility.Collapsed;
                                //var index = ContentEntitiyList.FindIndex(c => c.CatalogId == p);
                                //var data = ContentEntitiyList.Take(index).Sum(c => c.RealHegiht);
                                //ScrollViewerMainText.ScrollToVerticalOffset(data);
                                var data = TempList.Find(c => c.CatalogId == p);
                                var data1 = CatalogList.Find(c => c.CataLogId == p);
                                CurrentContent = data;
                                ContentText = data1.CataLogName + "\r\n" + data.MainContent;
                                IsCatalogChecked = false;
                                break;
                            }
                        case TextEnmu.Epub:
                            {
                                ScrollViewerMainText.Visibility = Visibility.Collapsed;
                                ScrollViewerMainText1.Visibility = Visibility.Visible;
                                var data = from item in ChapterEntityList where item.ChapterId == p select item;
                                if (data != null && data.ToList().Count == 1)
                                {
                                    webBrowser.NavigateToString(ConvertExtendedASCII(data.SingleOrDefault().ContentSource));
                                    CurrentChapterEntity = data.SingleOrDefault();
                                }
                                IsCatalogChecked = false;
                                break;
                            }
                    }

                }));
            }
        }
        private RelayCommand _SeparateDirectoryCommand;
        /// <summary>
        /// 分离目录
        /// </summary>
        public RelayCommand SeparateDirectoryCommand
        {
            get
            {
                return _SeparateDirectoryCommand ?? (_SeparateDirectoryCommand = new RelayCommand(() =>
                {
                    ProcessingText();
                    IsCatalogChecked = false;
                    IsMenuChecked = true;
                }));
            }
        }
        #endregion

        #region 方法
        private void WebBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if ((sender as System.Windows.Controls.WebBrowser).Document == null) return;
            ((sender as System.Windows.Controls.WebBrowser).Document as mshtml.HTMLDocumentEvents_Event).oncontextmenu -= new mshtml.HTMLDocumentEvents_oncontextmenuEventHandler(ExtendFrameControl_oncontextmenu);
            ((sender as System.Windows.Controls.WebBrowser).Document as mshtml.HTMLDocumentEvents_Event).oncontextmenu += new mshtml.HTMLDocumentEvents_oncontextmenuEventHandler(ExtendFrameControl_oncontextmenu);
            mshtml.HTMLDocument dom = (mshtml.HTMLDocument)webBrowser.Document; //定义HTML
            if (dom.documentElement == null) return;
            dom.documentElement.style.overflow = "hidden";    //隐藏浏览器的滚动条 
        }

        private void WebBrowser1_Loaded(object sender, RoutedEventArgs e)
        {
            if ((sender as System.Windows.Controls.WebBrowser).Document == null) return;
            ((sender as System.Windows.Controls.WebBrowser).Document as mshtml.HTMLDocumentEvents_Event).oncontextmenu -= new mshtml.HTMLDocumentEvents_oncontextmenuEventHandler(ExtendFrameControl_oncontextmenu);
            ((sender as System.Windows.Controls.WebBrowser).Document as mshtml.HTMLDocumentEvents_Event).oncontextmenu += new mshtml.HTMLDocumentEvents_oncontextmenuEventHandler(ExtendFrameControl_oncontextmenu);
            mshtml.HTMLDocument dom = (mshtml.HTMLDocument)webBrowser.Document; //定义HTML
            if (dom.documentElement == null) return;
            dom.documentElement.style.overflow = "hidden";    //隐藏浏览器的滚动条 
        }
        bool ExtendFrameControl_oncontextmenu()
        {
            Console.WriteLine(false + "已经屏蔽右键");
            return false;
        }

        /// <summary>
        /// webbrowser解决中文乱码问题 good
        /// </summary>
        /// <param name="HTML"></param>
        /// <returns></returns>
        private string ConvertExtendedASCII(string HTML)
        {
            string retVal = "";
            char[] s = HTML.ToCharArray();

            foreach (char c in s)
            {
                if (Convert.ToInt32(c) > 127)
                    retVal += "&#" + Convert.ToInt32(c) + ";";
                else
                    retVal += c;
            }

            return retVal;
        }

        bool IsCataLog = false;
        CatalogEntity catalogEntity = new CatalogEntity();
        ContentEntity contentEntity = new ContentEntity();
        void ProcessingText()
        {
            List<CatalogEntity> catalogEntities = new List<CatalogEntity>();
            List<ContentEntity> contentEntities = new List<ContentEntity>();
            string[] AllTextStr = File.ReadAllLines(FilePath, Encoding.Default);
            //string[] temp =AllContent.Split()
            //第8章 老宅
            string pattern = @"第\w+章";
            if (!string.IsNullOrWhiteSpace(Catalog))
                pattern = Catalog;
            for (int index = 0; index < AllTextStr.Length; index++)
            {

                if (index == 0)
                {
                    catalogEntity.CataLogId = Guid.NewGuid().ToString();
                    catalogEntity.CataLogName = "简介";
                    contentEntity.CatalogId = catalogEntity.CataLogId;
                }

                if (Regex.IsMatch(AllTextStr[index], pattern))
                {
                    if (!string.IsNullOrWhiteSpace(contentEntity.MainContent))
                    {
                        contentEntities.Add(contentEntity);
                        contentEntity = new ContentEntity();
                        catalogEntities.Add(catalogEntity);
                        catalogEntity = new CatalogEntity();
                    }
                    IsCataLog = true;

                }
                else
                {
                    IsCataLog = false;
                }
                if (IsCataLog)
                {
                    catalogEntity.CataLogId = Guid.NewGuid().ToString();
                    catalogEntity.CataLogName = AllTextStr[index].Trim();
                    contentEntity.CatalogId = catalogEntity.CataLogId;
                }
                else
                {
                    contentEntity.MainContent += AllTextStr[index];
                }


            }

            TempList = contentEntities;
            CatalogList = catalogEntities;
        }

        private void MyToolWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (TempList != null && TempList.Count > 0)
                ContentText = TempList[0].MainContent;
        }

        private void ItemsControl_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            IsCatalogChecked = false;
        }

        private void ScrollViewerMainText_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            ScrollViewer scrollViewer = sender as ScrollViewer;
            double ht = ScrollViewerMainText.VerticalOffset;
            if (ht == scrollViewer.ContentVerticalOffset)
            {
                // 
                int index = TempList.FindIndex(c => c.CatalogId == CurrentContent.CatalogId);
                if (index <= (TempList.Count - 1))
                {
                    if (index < 0) return;
                    CurrentContent = TempList[index + 1];
                    ContentText = CurrentContent.MainContent;
                }
                ScrollViewerMainText.ScrollToHome();
            }
        }

        private void ScrollViewerMainText_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            double ht = ScrollViewerMainText.VerticalOffset;
            var scrollViewer = sender as ScrollViewer;
            var data = CatalogList.Find(c => c.CataLogId == CurrentContent.CatalogId);
            if (e.Delta > 0)
            {
                Console.WriteLine("正在向上滚动滑轮");
                if (ht == 0)
                {
                    int index = TempList.FindIndex(c => c.CatalogId == CurrentContent.CatalogId);
                    if (index >= 1)
                    {
                        CurrentContent = TempList[index - 1];
                        ContentText = CurrentContent.MainContent;
                    }
                }
            }
            else
            {
                Console.WriteLine("正在向下滚动滑轮");
                if (ht == scrollViewer.ScrollableHeight)
                {
                    ScrollViewerMainText.ScrollToVerticalOffset(0.1);
                    int index = TempList.FindIndex(c => c.CatalogId == CurrentContent.CatalogId);
                    if (index < 0) return;
                    if (index < (TempList.Count - 1))
                    {
                        CurrentContent = TempList[index + 1];
                        data = CatalogList.Find(c => c.CataLogId == CurrentContent.CatalogId);
                        ContentText = data.CataLogName + "\r\n" + CurrentContent.MainContent;
                    }
                }

            }

        }

        private void ScrollViewerMainText1_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            double ht = ScrollViewerMainText1.VerticalOffset;
            var scrollViewer = sender as ScrollViewer;
            if (e.Delta > 0)
            {
                Console.WriteLine("正在向上滚动滑轮");
                if (ht == 0)
                {
                    for (int index = 0; index < ChapterEntityList.Count; index++)
                    {
                        if (ChapterEntityList[index] == CurrentChapterEntity)
                        {
                            if (index > 0)
                            {
                                CurrentChapterEntity = ChapterEntityList[index - 1];
                                webBrowser.NavigateToString(ConvertExtendedASCII(CurrentChapterEntity.ContentSource));
                            }
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("正在向下滚动滑轮");
                if (ht == scrollViewer.ScrollableHeight)
                {
                    ScrollViewerMainText1.ScrollToVerticalOffset(0.1);
                    for (int index = 0; index < ChapterEntityList.Count; index++)
                    {
                        if (ChapterEntityList[index] == CurrentChapterEntity)
                        {
                            if (index < ChapterEntityList.Count - 1)
                            {
                                CurrentChapterEntity = ChapterEntityList[index + 1];
                                webBrowser.NavigateToString(ConvertExtendedASCII(CurrentChapterEntity.ContentSource));
                            }
                        }
                    }
                }

            }
        }

        //        double ht = ScrollViewerMainText.VerticalOffset;
        //        var scrollViewer = sender as ScrollViewer;
        //            if (ht == 0)
        //            {
        //                int index = TempList.FindIndex(c => c.CatalogId == CurrentContent.CatalogId);
        //                if (index >= 1)
        //                {
        //                    CurrentContent = TempList[index - 1];
        //                    ContentText = CurrentContent.MainContent;
        //                }
        //}
        //            if (ht == scrollViewer.ContentVerticalOffset)
        //            {
        //                ScrollViewerMainText.ScrollToVerticalOffset(0.1);
        //                int index = TempList.FindIndex(c => c.CatalogId == CurrentContent.CatalogId);
        //                if (index< 0) return;
        //                if (index <= (TempList.Count - 1))
        //                {
        //                    CurrentContent = TempList[index + 1];
        //                    ContentText = CurrentContent.MainContent;
        //                }
        //            }
        #endregion
        ///// <summary>
        ///// Handles click on the button by displaying a message box.
        ///// </summary>
        ///// <param name="sender">The event sender.</param>
        ///// <param name="e">The event args.</param>
        //[SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Justification = "Sample code")]
        //[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Default event handler naming pattern")]
        //private void button1_Click(object sender, RoutedEventArgs e)
        //{
        //    MessageBox.Show(
        //        string.Format(System.Globalization.CultureInfo.CurrentUICulture, "Invoked '{0}'", this.ToString()),
        //        "NovelReadingWindow");
        //}
    }
}